import * as API from '../../../api/orderApi';
import * as util from '../../../utils/util';

var app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    num: false,
    switchOrders: 0,
    orderId: '1B830936AA9A1141BE24E1185769CA72',
    messageId: '',
    orderRule: true,
    scrollTop: 0,
    pingHeight: 0,
    isLoaded: false,
    hideModal: false,
    allShowNode: false,
    showNode: {
      node10: false,
      node20: false,
      node30: false,
      node40: false,
      node50: false,
      node60: false
    },
    companyName: '',
    companyId: '',
    order: {
      createBy: "",
      createDate: '',
      createMethod: "0",
      customCode: "",
      customContactMan: "",
      customContactWay: "",
      customId: "",
      customName: "",
      deliverStatus: "0",
      goodsCode: "",
      goodsDeliveryDate: '',
      goodsName: "",
      goodsNote: "",
      goodsNum: "0",
      goodsSpecification: "",
      goodsUnit: "",
      id: "",
      isNewRecord: false,
      orderDate: '',
      orderDeliveryAddress: "",
      orderNo: "",
      orderNote: "",
      publishStatus: "1",
      salesman: "",
      salesmanTel: "",
      shardingId: -1,
      updateBy: "",
      updateDate: '',
      overdue: false
    },
    nodeEventMap: {
      sendNum: 0,
      signedNum: 0
    }
  },
  callNumber: function (e) {
    wx.makePhoneCall({
      phoneNumber: this.data.order.salesmanTel
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      orderId: options.orderId || '',
      messageId: options.messageId || ''
    })
    this.getData()
  },
  // 从详情进来
  getData: function () {
    API.getEventList({
      orderId: this.data.orderId
    }).then(res => {
      wx.stopPullDownRefresh();
      if (!res) return;
      this.setTuggle(res)
    }, err => {
      wx.stopPullDownRefresh();
      util.toast('读取订单数据失败，请稍后再试');
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        })
      }, 1500);
    })
  },
  setTuggle(res) {
    const ExpireDate = res.order.changedDate || res.order.goodsDeliveryDate;
    const now = new Date().getTime();
    const expire = new Date(ExpireDate).setHours(23, 59, 59);
    const overdue = now > expire;
    let data = {
      order: res.order,
      nodeEventMap: res.nodeEventMap,
      nodes: {},
      orderByDate: [],
      showNode: {
        node10: false,
        node20: false,
        node30: false,
        node40: false,
        node50: false,
        node60: false
      },
      isLoaded: true,
      overdue: overdue,
      companyName: res.company && res.company.name,
      // companyId: res.company && res.company.id
    };
    if (res.nodeList && res.nodeList.length) {
      res.nodeList.forEach(item => {
        data.nodes['node' + item.nodeId] = item;
        let orderData = res.nodeEventMap['event' + item.nodeId]
        orderData.map((param) => {
          param.isOpen = false
          data.orderByDate.push(param)
        })
      });
      data.orderByDate.sort((a, b) => {
        return b.date - a.date
      })
      var arr = [];
      data.orderByDate.map((item) => {
        item.isOpen = true;
        data.showNode['node' + item.nodeId] = true
        arr.push({
          nodeId: item.nodeId
        })
      });
      this.setData(data);
    }
    this.allopenSwitch()
  },
  follow() {},
  // 遮罩层
  toNodeOrder() {
    this.setData({
      switchOrders: 0,
      orderRule: true,
      hideModal: false
    })
  },
  toDateOrder() {
    this.setData({
      switchOrders: 1,
      orderRule: false,
      hideModal: false
    })
    // this.checkScrollIntoView()
  },
  allShow(option) {
    var that = this
    let postBody = {
      orderId: this.data.orderId,
      shardingId: this.data.order.shardingId
    }
    let data = {
      order: this.data.order || [],
      // custom: res.custom,
      nodeEventMap: this.data.nodeEventMap || [],
      nodes: this.data.nodes || [],
      showNode: {
        node10: false,
        node20: false,
        node30: false,
        node40: false,
        node50: false,
        node60: false
      },
      orderByDate: this.data.orderByDate || '',
      isLoaded: this.data.isLoaded || false,
      overdue: this.data.overdue || false,
      showNode: this.data.showNode || false,
      allShowNode: this.data.allShowNode || false
    };

    if (option.currentTarget.dataset.id == '0') {
      // API.updateNodeStatus(postBody).then(res => {
      //   for (let item in data.nodeEventMap) {
      //     if (data.nodeEventMap[item].length > 0) {
      //       let itemNum = item.replace("event", '')
      //       let num = data.nodeEventMap[item]
      //       data.showNode['node' + itemNum] = true
      //       num.map(function (param) {
      //         param.isOpen = true
      //       })
      //     }
      //   }
      //   // that.setData({
      //   data.allShowNode = true
      //   // })
      //   that.setData(data)
      // }, err => {
      //   util.toast('读取订单数据失败，请稍后再试');
      //   setTimeout(() => {
      //     wx.navigateBack({
      //       delta: 1
      //     })
      //   }, 1500);
      // })
      for (let item in data.nodeEventMap) {
        if (data.nodeEventMap[item].length > 0) {
          let itemNum = item.replace("event", '')
          let num = data.nodeEventMap[item]
          data.showNode['node' + itemNum] = true
          num.map(function (param) {
            param.isOpen = true
          })
        }
      }
      // that.setData({
      data.allShowNode = true
      // })
      that.setData(data)
    } else {
      for (let item in data.nodeEventMap) {
        if (data.nodeEventMap[item].length > 0) {
          let itemNum = item.replace("event", '')
          data.showNode['node' + itemNum] = false
          let num = data.nodeEventMap[item]
          num.map(function (param) {
            param.isOpen = false
          })
        }
      }
      data.allShowNode = false
      that.setData(data)
    }

  },
  formatDate: function (timeStamp) {
    return yyMMddFormatWith(timeStamp);
  },
  informaJoin() {},
  // 遮罩层
  modalOpen() {
    this.setData({
      hideModal: true
    })
  },
  showTap(option) {
    // option.currentTarget.dataset.show=false
  },
  nagBack() {
    wx.navigateBack({
      delta: 1
    })
  },
  hideTap(option) {
    let data = {
      order: this.data.order,
      // custom: res.custom,
      nodeEventMap: this.data.nodeEventMap,
      nodes: this.data.nodes,
      orderByDate: this.data.orderByDate,
      isLoaded: this.data.isLoaded,
      overdue: this.data.overdue,
      showNode: this.data.showNode
    };
    data.nodeEventMap['event' + option.currentTarget.dataset.id].map((item, index) => {
      if (option.currentTarget.dataset.hide == "hide") {
        item.isOpen = false
        data.showNode['node' + option.currentTarget.dataset.id] = false
      } else {
        item.isOpen = true
        data.showNode['node' + option.currentTarget.dataset.id] = true
      }
    })
    this.setData(data)
    this.allopenSwitch()
  },
  // 根据展开状态同步全部展开状态
  allopenSwitch() {
    if (this.data.orderByDate) {
      let len = this.data.orderByDate.length
      let arr = []
      let arrHide = []
      this.data.orderByDate.map((item) => {
        if (item.isOpen) {
          arr.push(item.isOpen)
        } else {
          arrHide.push(item.isOpen)
        }
      })
      if (arr.length == len) {
        // this.allShowNode=false
        this.setData({
          allShowNode: true
        })
      }
      if (arrHide.length == len) {
        this.setData({
          allShowNode: false
        })
      }
    }
  },

  // 页面加载完毕
  onShow: function () {},
  onPageScroll: function (e) {},
  onPullDownRefresh: function () {
    this.getData();
    this.informaJoin()
  },
  phoneCall: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.replyPhone
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.removeStorage({
      key: 'choosedClient'
    });
  }
});